<!-- eslint-disable no-undef -->
<template>
  <div class="main-content">
    <!-- chart模板 -->
    <el-card class="card">
      <div
        ref="chartDom"
        :style="{ height: `${props.chartHeight}`, width: `${chartWidth}` }"
      ></div>
    </el-card>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, watch, onMounted } from 'vue'
import 'default-passive-events'
const chartWidth = ref('100%')
// 定义 ref 来获取 DOM 元素
const chartDom = ref(null)
let chartStore = null
// 定义 emit 函数
const emit = defineEmits(['get_chart_x'])
// 定义 props
const props = defineProps({
  click_on: {
    type: String,
    default() {
      return 'false'
    }
  },
  chartHeight: {
    type: String,
    default() {
      return '30vh'
    }
  },
  chartOPtions: {
    type: Object,
    default() {
      return {}
    }
  }
})
watch(
  props.chartOPtions,
  // eslint-disable-next-line no-unused-vars
  (newValue, oldValue) => {
    initChart(newValue)
  },
  { deep: true }
)

function initChart(option) {
  // 确保 DOM 已经加载
  if (chartDom.value) {
    if (chartStore) {
      chartStore.dispose()
    }
    let myChart = echarts.init(chartDom.value)
    chartStore = myChart
    option && chartStore.setOption(option)

    // 图形的自适应显示
    window.addEventListener(
      'resize',
      () => {
        chartStore.resize()
      },
      { passive: true }
    )
    // 获取目标 div 元素
    const container = document.querySelector('.main-content')
    // 创建一个 ResizeObserver 实例
    const resizeObserver = new ResizeObserver(() => {
      // 每次 div 大小变化时调整图表大小
      chartStore.resize()
    })
    // 监听 div 大小变化
    resizeObserver.observe(container)

    if (props.click_on == 'true') {
      // 点击图形获取X轴的值
      let zr = myChart.getZr()
      zr.on(
        'click',
        (params) => {
          let pointInPixel = [params.offsetX, params.offsetY]
          let pointInGrid = myChart.convertFromPixel('grid', pointInPixel)
          if (myChart.containPixel('grid', pointInPixel)) {
            let chart_x = myChart.getOption().xAxis[0].data[pointInGrid[0]]
            emit('get_chart_x', chart_x)
          }
        },
        {
          passive: true // 添加passive选项
        }
      )
    }
  }
}
// 在组件挂载时初始化图表
onMounted(() => {
  initChart(props.chartOPtions)
})
</script>

<style scoped>
.main-content {
  height: 100%;
  width: 100%;
}
.card {
  transition: box-shadow 0.3s ease, transform 0.3s ease;
}

.card:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
  transform: translateY(-4px);
}
</style>
